package com.example.rbacmanage.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.SecureRandom;
import java.util.Properties;

public class EmailSenderUtil {
    private static final String CHAR_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    private static SecureRandom random = new SecureRandom();

    public static String generateCode(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHAR_LIST.length());
            sb.append(CHAR_LIST.charAt(randomIndex));
        }
        return sb.toString();
    }
    public static void sendEmail(String to, String subject, String content) {
        String fromEmail = "724344579@qq.com";
        String password="sgjxwniwdpjabbgc";
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(fromEmail, password);
            }
        });

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(fromEmail));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(content);
            Transport.send(mimeMessage);
            System.out.println("Message sent successfully...");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    public static String getEmailCode(String toEmail) {
        String subject = "你的验证码:"; // 邮件主题
        String verificationCode = generateCode(6); // 生成6位验证码
        String message = "你的验证码是: " + verificationCode; // 邮件内容，包含验证码
        sendEmail(toEmail, subject, message); // 发送邮件和验证码
        return verificationCode;
    }
    public static void main(String[] args) {
        String toEmail = "724344579@qq.com"; // 收件人邮箱地址
        String subject = "你的验证码:"; // 邮件主题
        String verificationCode = generateCode(6); // 生成6位验证码
        String message = "你的验证码是: " + verificationCode+",30分钟内有效"; // 邮件内容，包含验证码
        sendEmail(toEmail, subject, message); // 发送邮件和验证码
    }
}
